package com.ruoyi.course.service.impl;

import java.util.List;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.mapper.TChapterMapper;
import com.ruoyi.course.mapper.TCourseUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.course.mapper.TCourseMapper;
import com.ruoyi.course.domain.TCourse;
import com.ruoyi.course.service.ITCourseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 课程Service业务层处理
 *
 * @author Bandit
 * @date 2022-11-01
 */
@Service
public class TCourseServiceImpl implements ITCourseService
{
    @Autowired
    private TCourseMapper tCourseMapper;

    @Autowired
    private TChapterMapper tChapterMapper;

    @Autowired
    private TCourseUserMapper tCourseUserMapper;

    /**
     * 查询课程
     *
     * @param id 课程主键
     * @return 课程
     */
    @Override
    public TCourse selectTCourseById(Long id)
    {
        return tCourseMapper.selectTCourseById(id);
    }

    /**
     * 查询课程列表
     *
     * @param tCourse 课程
     * @return 课程
     */
    @Override
    public List<TCourse> selectTCourseList(TCourse tCourse)
    {
        return tCourseMapper.selectTCourseList(tCourse);
    }

    @Override
    public List<TCourse> selectCurrentUserTCourseList() {
        Long userId = SecurityUtils.getUserId();
        return tCourseMapper.selectTCourseByUserId(userId);
    }

    /**
     * 新增课程
     *
     * @param tCourse 课程
     * @return 结果
     */
    @Override
    public int insertTCourse(TCourse tCourse)
    {
        tCourse.setCreatedBy(SecurityUtils.getUserId());
        return tCourseMapper.insertTCourse(tCourse);
    }

    /**
     * 修改课程
     *
     * @param tCourse 课程
     * @return 结果
     */
    @Override
    public int updateTCourse(TCourse tCourse)
    {
        return tCourseMapper.updateTCourse(tCourse);
    }

    /**
     * 批量删除课程
     *
     * @param ids 需要删除的课程主键
     * @return 结果
     */
    @Override
    public int deleteTCourseByIds(Long[] ids)
    {
        return tCourseMapper.deleteTCourseByIds(ids);
    }

    /**
     * 删除课程信息
     *
     * @param id 课程主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTCourseById(Long id)
    {
        // 删除课程级联删除 章节、选课学生
        Long[] chapterIds = tChapterMapper.selectIdsByCourseId(id);
        tChapterMapper.deleteTChapterByIds(chapterIds);
        // 删除选课学生关联
        tCourseUserMapper.deleteTCourseUserByCourseId(id);
        return tCourseMapper.deleteTCourseById(id);
    }
}
